package perso.android.savethemage.v1;

import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.engine.handler.physics.PhysicsHandler;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.RotationModifier;
import org.andengine.entity.modifier.ScaleAtModifier;
import org.andengine.entity.primitive.Line;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.Sprite;
import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.extension.svg.opengl.texture.atlas.bitmap.SVGBitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource;
import org.andengine.opengl.texture.atlas.buildable.builder.BlackPawnTextureAtlasBuilder;
import org.andengine.opengl.texture.atlas.buildable.builder.ITextureAtlasBuilder.TextureAtlasBuilderException;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.ITiledTextureRegion;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.util.debug.Debug;
import org.andengine.util.modifier.IModifier;
import org.andengine.util.modifier.IModifier.IModifierListener;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;

import android.util.Log;

public class SortDeBouleRebondissante extends ASort{

	private int nbRebondMax = 0;
	final int  PRECISION = 40;
	
	private Scene circleScene, circleTraceScene;
	//private AnimatedSprite cercleSpriteB;
	private int sizeCircle;
	private ScaleAtModifier entityModifier;
	
	private  Sprite[] bouleList = new Sprite[PRECISION];
	private  Sprite boule;
	private boolean trace = true;

	private TiledTextureRegion mFaceTextureRegionRebondissant;
	private BuildableBitmapTextureAtlas mBitmapTextureAtlasRebondissant;

	private PhysicsWorld physicsWorld;
	
	private BitmapTextureAtlas mBitmapTextureAtlasCercleTestRebondissant;
	private ITextureRegion mTestCercleRebondissant;
	
	
	private Sprite cercleSprite;
	private ITextureRegion mParticleTextureRegionRebondissant;
	private BitmapTextureAtlas mBitmapTextureAtlasParticuleRebondissant;
	private BitmapTextureAtlas mBitmapTextureAtlasCercleTestRebondissantB;
	private ITextureRegion mTestCercleRebondissantB;
	private Sprite cercleSpriteB;
	
	public SortDeBouleRebondissante(int nbMaxMechantCroise, SortPossible sortP, int monNbRebondMax){
		super.instancier(nbMaxMechantCroise, sortP);
		this.nbRebondMax = monNbRebondMax;
	}

	@Override
	public void onCreateResources(String nomFichierSVG, String nomParticulesPNG, int pWidth, int pHeight, int NbLigneDansSprite, int nbColonneDansSprite, GameActivity gameActivityA) {
		this.onCreateResources(nomFichierSVG, "cercle3", nomParticulesPNG, NbLigneDansSprite, nbColonneDansSprite, gameActivityA);
		Log.e("Misa.SortDeBouleRebondissante", "OnCreatRessources One");
		this.scene = gameActivityA.scene;
		
	}
	
	
	public void onCreateResources(String nomFichierSVG, String nomFichier2SVG, String nomParticulesPNG, 
			int NbLigneDansSprite, int nbColonneDansSprite, GameActivity gameActivityA) {
	/*
	    this.mBitmapTextureAtlasRebondissant = new BuildableBitmapTextureAtlas(gameActivityA.getTextureManager(), 512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mFaceTextureRegionRebondissant = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlasRebondissant, gameActivityA.getApplicationContext(), 
				nomFichier2SVG+".png" , 1, 1);

		try {
			this.mBitmapTextureAtlasRebondissant.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 0));
			this.mBitmapTextureAtlasRebondissant.load();
		} catch (TextureAtlasBuilderException e) {
			Debug.e(e);
		}
		//*/
		this.vertexBufferObjectManager = gameActivityA.getVertexBufferObjectManager();
		
		this.mBitmapTextureAtlasCercleTestRebondissant = new BitmapTextureAtlas(gameActivityA.getTextureManager(), 1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mBitmapTextureAtlasCercleTestRebondissantB = new BitmapTextureAtlas(gameActivityA.getTextureManager(), 1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		
		
		this.mTestCercleRebondissant = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlasCercleTestRebondissant, 
				gameActivityA.getApplicationContext(), "cercleA.png", 0, 0);
		
		this.mTestCercleRebondissantB = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlasCercleTestRebondissantB, 
				gameActivityA.getApplicationContext(), "cercleB.png", 0, 0);

		this.mBitmapTextureAtlasCercleTestRebondissant.load();
		this.mBitmapTextureAtlasCercleTestRebondissantB.load();
		
		this.mBitmapTextureAtlasParticuleRebondissant = new BitmapTextureAtlas(gameActivityA.getTextureManager(), 16, 16, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mParticleTextureRegionRebondissant = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlasParticuleRebondissant, 
				gameActivityA.getApplicationContext(), nomParticulesPNG+".png", 0, 0);
		this.mBitmapTextureAtlasParticuleRebondissant.load();
		//*/
		
	}
	
	@Override
	public void appli(final PhysicsWorld mPhysicsWorld) {
		

		//Sert a le positionner, mais on le vois pas
		final float centreX = 0;
		final float centreY = 0;
		final int cpt = 0;
	//	this.sizeCircle = maSizeCircle;
		
		this.sizeCircle = (int) (CameraDim.CAMERA_WIDTH*0.5f *CameraDim.CAMERA_HEIGHT/CameraDim.CAMERA_WIDTH);
		
		//this.physicsWorld = mPhysicsWorld;
		
		circleScene = new Scene();
		circleScene.setBackgroundEnabled(false);
		
		circleTraceScene = new Scene();
		circleTraceScene.setBackgroundEnabled(false);

		cercleSprite = new Sprite(centreX, centreY, this.sizeCircle, this.sizeCircle, this.mTestCercleRebondissant , this.vertexBufferObjectManager);
		
		entityModifier = new ScaleAtModifier(0.7f , 0.1f, 1, this.sizeCircle/2, this.sizeCircle/2 );
		cercleSprite.registerEntityModifier(entityModifier); 
		cercleSprite.registerEntityModifier(new RotationModifier(50, 1, 800));
		circleScene.attachChild(cercleSprite);
		
		
		cercleSpriteB = new Sprite(centreX, centreY, this.sizeCircle, this.sizeCircle, this.mTestCercleRebondissantB , this.vertexBufferObjectManager);	
		
		entityModifier = new ScaleAtModifier(0.7f , 0.1f, 1, this.sizeCircle/2, this.sizeCircle/2 );
		cercleSpriteB.registerEntityModifier(entityModifier); 
		cercleSpriteB.registerEntityModifier(new RotationModifier(50, 800, 1));
		circleScene.attachChild(cercleSpriteB);
		
		

		face = new AnimatedSprite(centreX, centreY,this.sizeCircle, this.sizeCircle, this.mFaceTextureRegionRebondissant, this.vertexBufferObjectManager);

        this.setEnable(mPhysicsWorld,false);
        
        
        Log.e("Misa.SortDeBouleRebondissante", "OnPopulate");

		//this.physicsWorld = mPhysicsWorld;
		//this.scene = mScene;

		Log.e("Misa.SortDeBouleRebondissante", "SUperPasse");
		
		circleScene.registerUpdateHandler(new TimerHandler(8f, new ITimerCallback() {
			public void onTimePassed(final TimerHandler pTimerHandler){
				
				
				Log.e("Misa.SortDeBouleRebondissante", "Panda");
				
				for(int i = 0; i < bouleList.length; i++) {
					
						if(bouleList[i] != null) {
						
							mPhysicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(
								 (Sprite)bouleList[i]).getBody().setActive(false);
						}
					
				}
				
				try {
						circleTraceScene.detachChildren();
				} catch(Exception  e) {
					Log.e("Misa.SortDeBouleRebondissante", "circleTrascene" + e.toString());
				}
				try {
						circleScene.detachChildren();
				} catch(Exception  e) {
						Log.e("Misa.SortDeBouleRebondissante", "circleScene" + e.toString());
				}
				try {
						scene.detachChild(circleScene);
				} catch(Exception  e) {
						Log.e("Misa.SortDeBouleRebondissante", "scene" + e.toString());
				}
			
				//circleTraceScene.detachSelf();
				//circleScene.detachChild(boule);
				//circleScene.detachChild(circleTraceScene);
				
				
				
			//	circleScene.detachSelf();
				//circleScene.reset();
			//	trace = false;
				//scene.detachChild(circleScene);
			}              
		}));

		scene.attachChild(circleScene);
        
	}
	

	@Override
	public void onCreateScene(PhysicsWorld mPhysicsWorld, int maSizeCircle, int laPrecision){

	}
	
	/*
	
	@Override
	public void action(AMechant mechant, GameActivity svtm){
		Log.d("Misa.SortDeBouleRebondissante", "Colisionnnnnnnnnnn "+this.NbMechantRencontre);
		this.NbMechantRencontre++;
		if(this.NbMechantRencontre<1){
			
		}
		this.effet(mechant, svtm);
		if(mechant.vie <= 0)
			//svtm.destruction(mechant);
			;
		else{
			//Changement de couleur ici
			float ratio = 1 - (mechant.vieTotal/mechant.vie);
			//this.face.setColor(mechant.face.getColor().getRed(), mechant.face.getColor().getGreen()-ratio, mechant.face.getColor().getBlue()-ratio);
		}
		//Log.d("Misa.SortDeBouleRebondissante", "Vie du mechant :"+mechant.vie);
	}
	*/
	@Override
	public void effet(AMechant mechant, GameActivity svtm) {
		//Log.e("Misa.SavaTheMage", "Boum, collision");
		if(mechant instanceof MechantDeBase){
			mechant.vie = mechant.vie - 80;
		
		} else {
			Log.e("Misa.Entite", "Aucun effet sur le monstre!!!");
		}
		if(mechant.vie <= 0)
			svtm.destruction(mechant);
	}
	
	
	public void addCircleCollision(PhysicsWorld mPhysicsWorld,  final float pX, final float pY) {
	
		float r = (this.sizeCircle/2)*0.74f;
		float pi = 3.141592f;
		float step = (2*pi)/PRECISION;
		
		for(int i = 0; i < PRECISION; i++) {
			float x1 = (float) (r * Math.cos(i*step));
			float y1 = (float) (r * Math.sin(i*step));
		
			final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(1, 0.2f, 0.6f);
			
			final Sprite bouleSprite = new Sprite(x1 + pX, y1 + pY, this.mParticleTextureRegionRebondissant, this.vertexBufferObjectManager);
			bouleSprite.setVisible(false);
			bouleList[i] = bouleSprite;
			
			final Body body2 = PhysicsFactory.createCircleBody(mPhysicsWorld, bouleSprite, BodyType.StaticBody, wallFixtureDef);
		
			mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(bouleSprite, body2, true, true));

			
			circleTraceScene.attachChild(bouleSprite);

		}

		circleScene.attachChild(circleTraceScene);
		

		FixtureDef bouleParam = PhysicsFactory.createFixtureDef(0.2f, 1f, 0.6f);

		 boule = new Sprite(pX+20, pY+20, this.mParticleTextureRegionRebondissant, this.vertexBufferObjectManager);
		boule.setScale(3f);
		//boule.setColor(0.9f, 0.9f, 1f, 1);
		this.body = PhysicsFactory.createCircleBody(mPhysicsWorld, boule, BodyType.DynamicBody, bouleParam);

		Vector2 center = this.body.getWorldCenter();
		Vector2 force = new Vector2(0, 16 );
		this.body.applyLinearImpulse(force, center);
		//  body2.setLinearVelocity(8, 0);

		circleScene.attachChild(boule);
		mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(boule, this.body, true, true));
		
		
		
		circleScene.registerUpdateHandler(new IUpdateHandler() {
			public void reset() { }

			public void onUpdate(final float pSecondsElapsed) {
				if(trace)
					addTrace(circleScene, boule.getX(), boule.getY());
			}
		});
		
		
	}


	private void addTrace(final Scene pScene, float x, float y) {
		final Sprite boule = new Sprite(x,y, this.mParticleTextureRegionRebondissant, this.vertexBufferObjectManager);
		boule.setScale(0.5f);
		boule.setColor(0.90f, 0.90f, 1f);
		pScene.attachChild(boule);
		
	}

	@Override
	public void onPopulateScene(final PhysicsWorld mPhysicsWorld, final Scene mScene){
		

	}
	
	@Override
	public void setPosition(final PhysicsWorld mPhysicsWorld, final float pX, final float pY) {
		Log.e("Misa.SortDeBouleRebondissante", "setPosition");
		entityModifier.addModifierListener(new IModifierListener<IEntity>(){
			
			
			public void onModifierStarted(IModifier<IEntity> pModifier,
					IEntity pItem) {
				// 
				
			}
			public void onModifierFinished(IModifier<IEntity> pModifier,
					IEntity pItem) {
				
				addCircleCollision(mPhysicsWorld, pX, pY);
				
			}
		});

		Log.e("Misa.SortDeBouleRebondissante", "SetPossition 2");
		//this.face.setPosition(pX - this.sizeCircle/2, pY - this.sizeCircle/2);
		this.cercleSprite.setPosition(pX - this.sizeCircle/2, pY - this.sizeCircle/2);
		this.cercleSpriteB.setPosition(pX - this.sizeCircle/2, pY - this.sizeCircle/2);
	}

	@Override
	public void onDepopulateScene(PhysicsWorld mPhysicsWorld, Scene scene){
		/*
		scene.detachChild(circleScene);
		if(this.circleScene.getChildCount() > 0) {
			mPhysicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape((AnimatedSprite)this.circleScene.getLastChild()).getBody().setActive(false);
	       // Body b = mPhysicsWorld.getPhysicsConnectorManager().findBodyByShape(this.face);
	        this.circleScene.detachChild(this.circleScene.getLastChild());
		}//*/
	}
}

